/**
 * Copyright (c) 2011 Baidu.com, Inc. All Rights Reserved
 */
package net.dreamlu.api.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.baidu.bae.api.fetchurl.BaeFetchurl;
import com.baidu.bae.api.fetchurl.BaeFetchurlFactory;
import com.baidu.bae.api.fetchurl.BasicNameValuePair;
import com.baidu.bae.api.fetchurl.NameValuePair;
import com.jfinal.kit.StringKit;

/**
 * 进行http访问的基本类
 * 
 * @author chenhetong(chenhetong@baidu.com)
 * 
 */
public class HttpUtil {

    private static final String DEFAULT_CHARSET = "UTF-8";

    public static final String METHOD_POST = "POST";

    public static final String METHOD_GET = "GET";

    public static final int HTTPSTATUS_OK = 200;

    public static final int CONNECTIMEOUT = 5000;

    public static final int READTIMEOUT = 5000;

    /**
     * 通过get方法访问，默认编码为utf-8
     * 
     * @param url 访问的url地址
     * @param params 请求需要的参数
     * @return 返回请求响应的数据
     * @throws IOException
     */
    public static String doGet(String url, Map<String, String> params) throws IOException {
        return doGet(url, params, DEFAULT_CHARSET);
    }

    /**
     * 通过get方法访问
     * 
     * @param url 访问的url地址
     * @param params 请求需要的参数
     * @param charset 字符编码
     * @return 返回请求响应的数据
     * @throws IOException
     */
    public static String doGet(String url, Map<String, String> params, String charset)
            throws IOException {
        if (StringKit.isBlank(url) || params == null) {
            return null;
        }
        String response = null;
        url += "?" + buildQuery(params, charset);
        BaeFetchurl fetchUrl = BaeFetchurlFactory.getBaeFetchurl();
        String ctype = "application/x-www-form-urlencoded;charset=" + charset;
        fetchUrl.setHeader("Content-Type", ctype);
        fetchUrl.setHeader("User-Agent", "baidu-restclient-java-bae-1.0");
        fetchUrl.get(url);
        int httpCode = fetchUrl.getHttpCode();
        if (httpCode == HTTPSTATUS_OK) {
            response = fetchUrl.getResponseBody();
        } else {
            throw new IOException(fetchUrl.getErrmsg());
        }
        return response;

    }

    public static String doPost(String url, Map<String, String> params) throws IOException {
        return doPost(url, params, CONNECTIMEOUT, READTIMEOUT);
    }

    /**
     * 
     * 通过post方法请求数据，默认字符编码为utf-8
     * 
     * @param url 请求的url地址
     * @param params 请求的参数
     * @param connectTimeOut 请求连接过期时间
     * @param readTimeOut 请求读取过期时间
     * @return 请求响应
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> params, int connectTimeOut,
            int readTimeOut) throws IOException {
        return doPost(url, params, DEFAULT_CHARSET, connectTimeOut, readTimeOut);
    }

    /**
     * 
     * 通过post方法请求数据
     * 
     * @param url 请求的url地址
     * @param params 请求的参数
     * @param charset 字符编码格式
     * @param connectTimeOut 请求连接过期时间
     * @param readTimeOut 请求读取过期时间
     * @return 请求响应
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> params, String charset,
            int connectTimeOut, int readTimeOut) throws IOException {
        String response = null;
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        for (Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (StringKit.notBlank(key, value)) {
                paramsList.add(new BasicNameValuePair(key, value));
            }
        }
        String ctype = "application/x-www-form-urlencoded;charset=" + charset;
        BaeFetchurl fetchUrl = BaeFetchurlFactory.getBaeFetchurl();
        fetchUrl.setConnectTimeout(connectTimeOut);
        fetchUrl.setReadTimeout(readTimeOut);
        fetchUrl.setHeader("Content-Type", ctype);
        fetchUrl.setHeader("User-Agent", "baidu-restclient-java-bae-1.0");
        fetchUrl.setPostData(paramsList, charset);
        fetchUrl.post(url);
        int httpCode = fetchUrl.getHttpCode();
        if (httpCode == HTTPSTATUS_OK) {
            response = fetchUrl.getResponseBody();
        } else {
            throw new IOException(fetchUrl.getErrmsg());
        }
        return response;
    }

    /**
     * 
     * @param params 请求参数
     * @return 构建query
     */
    public static String buildQuery(Map<String, String> params, String charset) {
        if (params == null || params.isEmpty()) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Entry<String, String> entry : params.entrySet()) {
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            String key = entry.getKey();
            String value = entry.getValue();
            if (StringKit.notBlank(key, value)) {
                try {
                    sb.append(key).append("=").append(URLEncoder.encode(value, charset));
                } catch (UnsupportedEncodingException e) {}
            }
        }
        return sb.toString();

    }

    public static Map<String, String> splitQuery(String query, String charset) {
        Map<String, String> ret = new HashMap<String, String>();
        if (StringKit.notBlank(query)) {
            String[] splits = query.split("\\&");
            for (String split : splits) {
                String[] keyAndValue = split.split("\\=");
                if (StringKit.notBlank(keyAndValue) && keyAndValue.length == 2) {
                    try {
                        ret.put(keyAndValue[0], URLDecoder.decode(keyAndValue[1], charset));
                    } catch (UnsupportedEncodingException e) {}
                }
            }
        }
        return ret;
    }

}
